//
//  HomePageViewController.m
//  一点互助
//
//  Created by 张泊秋 on 16/8/19.
//  Copyright © 2016年 zhangboqiu. All rights reserved.
//

#import "HomePageViewController.h"
#import "UIViewController+NavagitionBar.h"
#import "PositioningViewController.h"
#import "SearchViewController.h"
#import "ResponseManager.h"
#import "FTHomeTableViewCell.h"
#import "FTHomePageHeaderView.h"
#import "WishesModel.h"
#import "FBProgressView.h"
#import "UserState.h"
#import "DetailViewController.h"
#import <UIImageView+WebCache.h>


@import CoreLocation;
typedef void(^myblock)(void);
@interface HomePageViewController ()<UITableViewDelegate,UITableViewDataSource,CLLocationManagerDelegate>
@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *dataSource;
@property (nonatomic, strong) UITextField *textField;
@property (strong, nonatomic) NSMutableDictionary *HomeLuckyBagDataSource;
@property (strong, nonatomic) NSMutableArray *headerViewModelArray;
@property (strong, nonatomic) FTHomePageHeaderView *headerView;
@property (nonatomic,strong) CLLocationManager *locationManager;
@end

@implementation HomePageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    UINib *nib = [UINib nibWithNibName:@"FTHomeTableViewCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:kHomeTableViewCell];
    [self.view addSubview:self.tableView];
    self.headerView = [FTHomePageHeaderView loadHeaderView];
    self.tableView.tableHeaderView = self.headerView;
    self.headerView.frame = CGRectMake(0, 0, kScreenWidth, 400*kScreenHeightScale);
    self.headerView.ownerVC = self;
    [self locationGet];
    [self setupCenterItemWithText:@"项目、用户" action:@selector(searchButtonTaped:)];
    [self getSlideBar];
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self getAllNetWork];
    self.tabBarController.tabBar.hidden = NO;
    UserState *user = [[UserState alloc]init];
    if ([user.location isKindOfClass:[NSString class]]) {
        self.navigationItem.leftBarButtonItem = [self barButtonItemWithImageName:@"down" text:user.location action:@selector(positioningButtonTaped:)];
    }

}

- (void)headerViewScrollView {
    
    
}
-(void)refreshHeaderView{
    self.headerView.todayGetLabel.text = [NSString stringWithFormat:@"%@/%@",self.HomeLuckyBagDataSource[@"today_get"],self.HomeLuckyBagDataSource[@"unit"]];
    self.headerView.homeLuckyLabel.text = [NSString stringWithFormat:@"%@%@获得%@返现",self.HomeLuckyBagDataSource[@"info"][@"user_nicename"],self.HomeLuckyBagDataSource[@"info"][@"mobile"],self.HomeLuckyBagDataSource[@"info"][@"coin"]];
    self.headerView.totdayProgress.progress = [self.HomeLuckyBagDataSource[@"today_get"] floatValue]/[self.HomeLuckyBagDataSource[@"today"] floatValue];
    self.headerView.todayTotalLabel.text = [NSString stringWithFormat:@"%@/%@",self.HomeLuckyBagDataSource[@"today"],self.HomeLuckyBagDataSource[@"unit"]];
    self.headerView.allLabel.text = self.HomeLuckyBagDataSource[@"all"];
    self.headerView.allUnit.text = self.HomeLuckyBagDataSource[@"unit"];

}
-(void)getAllNetWork{
    [FBProgressView showWithMessage:nil];
    [self getWishNetwork];
    [self getHomeLuckBag ];
    [self getSlideBar];
    
}
-(void)locationGet{
    if ([CLLocationManager locationServicesEnabled]) {
        //开始定位用户的位置
        [self.locationManager startUpdatingLocation];
        //每隔多少米定位一次（这里的设置为任何的移动）
        self.locationManager.distanceFilter=kCLDistanceFilterNone;
        //设置定位的精准度，一般精准度越高，越耗电（这里设置为精准度最高的，适用于导航应用）
        self.locationManager.desiredAccuracy=kCLLocationAccuracyBestForNavigation;
    }else
    {//不能定位用户的位置
        //1.提醒用户检查当前的网络状况
        //2.提醒用户打开定位开关
    }
    
    
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    __weak typeof(self) myself = self;
    CLLocation *newLocation = locations[0];
    CLLocationCoordinate2D oldCoordinate = newLocation.coordinate;
    NSLog(@"旧的经度：%f,旧的纬度：%f",oldCoordinate.longitude,oldCoordinate.latitude);
    [self.locationManager stopUpdatingLocation];
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:newLocation
                   completionHandler:^(NSArray *placemarks, NSError *error){
                       for (CLPlacemark *place in placemarks) {
                           NSLog(@"name,%@",place.name);                       // 位置名
                           NSLog(@"thoroughfare,%@",place.thoroughfare);       // 街道
                           NSLog(@"subThoroughfare,%@",place.subThoroughfare); // 子街道
                           NSLog(@"locality,%@",place.locality);               // 市
                           UserState *user = [[UserState alloc]init];
                           user.location = place.locality;
                           myself.navigationItem.leftBarButtonItem = [myself barButtonItemWithImageName:@"down" text:user.location action:@selector(positioningButtonTaped:)];
                           NSLog(@"subLocality,%@",place.subLocality);         // 区
                           NSLog(@"country,%@",place.country);                 // 国家
                       }
                       
                   }];
    
    //停止更新位置（如果定位服务不需要实时更新的话，那么应该停止位置的更新）
    
}
-(CLLocationManager *)locationManager{
    if (!_locationManager) {
        _locationManager = [[CLLocationManager alloc]init];
        [_locationManager requestWhenInUseAuthorization];
        _locationManager.delegate = self;
        _locationManager.distanceFilter = kCLDistanceFilterNone;
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    }
    return _locationManager;
}


BOOL  stop1 = false;
BOOL  stop2 = false;
BOOL  stop3 = false;
-(void)checkRequestFinished{
    if (stop1 && stop2 && stop3 ) {
        [FBProgressView hide];
    }
}
-(void)getWishNetwork{
    __weak typeof(self) myself = self;
    [ResponseManager startGetRequestWithURLString:kGetWishListURL parameters:nil completionHandler:^(FBResponse *response) {
        stop1 = true;
        if (response.success) {
//           PLLOG(@"%@",response.resultValue);
            [myself checkRequestFinished];
            NSArray *arr = [WishesModel modelArrayWithDictionaryArr:response.resultValue];
            myself.dataSource = [arr mutableCopy];
//            [myself.tableView reloadData];
            [myself.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade];
        }else{
            [self addAlertControllerWithTitle:@"提示" message:@"请求失败" actionNum:2 style:UIAlertControllerStyleAlert handler:^(UIAlertAction *action) {
                [myself getWishNetwork];
            }];
        }
    }];
}
-(void)getHomeLuckBag{
    __weak typeof(self) myself = self;
    [ResponseManager startGetRequestWithURLString:kHomeLuckyBagURL parameters:nil completionHandler:^(FBResponse *response) {
        stop2 = true;
        if (response.success) {
            [myself checkRequestFinished];
            myself.HomeLuckyBagDataSource = [response.resultValue mutableCopy];
            [myself refreshHeaderView];
//            PLLOG(@"data:%@",myself.HomeLuckyBagDataSource);
        }
    }];

}
-(void)getSlideBar{
    __weak typeof(self) myself = self;
    [ResponseManager startGetRequestWithURLString:kSlideURL parameters:nil completionHandler:^(FBResponse *response) {
        stop3 = true;
        if (response.success) {
            [myself checkRequestFinished];
            PLLOG(@"Slider == %@",response.resultValue);
            NSMutableArray *imagViews = [NSMutableArray array];
            for (NSDictionary *dic in response.resultValue) {
                NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kGetScrollViewURL,dic[@"slide_pic"]]];
                [imagViews addObject:url];
            }
            self.headerView.images = [imagViews copy];
        }else{
        
        }
    }];
}




- (UIBarButtonItem *)barButtonItemWithImageName:(NSString *)imageName text:(NSString *)text  action:(SEL)action {
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, 60, 44);
    UIImage *image = [UIImage imageNamed:imageName];
    [button setTitleEdgeInsets:UIEdgeInsetsMake(0,-image.size.width - 27, 0, image.size.width )];
    [button setImageEdgeInsets:UIEdgeInsetsMake(0, button.titleLabel.bounds.size.width + 30, 0, -button.titleLabel.bounds.size.width)];
    [button setImage:image forState:UIControlStateNormal];
    [button setTitle:text forState:UIControlStateNormal];
    
    [button addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    button.titleLabel.font = [UIFont systemFontOfSize:15];
    
    
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button];
    return barButtonItem;
    
    
}


- (void)positioningButtonTaped:(UIButton *)sender {
    
    PositioningViewController *VC = [[PositioningViewController alloc]init];
    [self.navigationController pushViewController:VC animated:YES];
    
}

- (void)searchButtonTaped:(UIButton *)sender {
   SearchViewController *VC = [[SearchViewController alloc]init];
   [self.navigationController pushViewController:VC animated:YES];
                                         
}
#pragma mark --UITableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    FTHomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kHomeTableViewCell forIndexPath:indexPath];
    cell.model = self.dataSource[indexPath.row];
//    PLLOG(@"%@",self.dataSource);
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100 * kScreenHeightScale;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UINib *nib = [UINib nibWithNibName:@"HomeTinyHeaderView" bundle:nil];
    UIView *view = [[nib instantiateWithOwner:self options:nil]firstObject];
     return view;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 30 * kScreenHeightScale;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    DetailViewController *vc = [[DetailViewController alloc]init];
    vc.model = self.dataSource[indexPath.row];
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark --Lazy
-(NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}
-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

-(NSMutableDictionary *)HomeLuckyBagDataSource{
    if (!_HomeLuckyBagDataSource) {
        _HomeLuckyBagDataSource = [NSMutableDictionary dictionary];
    }
    return _HomeLuckyBagDataSource;
}
-(NSMutableArray *)headerViewModelArray{
    if (!_headerViewModelArray) {
        _headerViewModelArray = [NSMutableArray array];
    }
    return _headerViewModelArray;
}
#pragma mark --HomeHeaderViewDelegate



@end
